#!/usr/bin/env python

import logging
import messaging.sms

class Sms(object):
    '''SMS class
    
    @author Julot <andy.julot@gmail.com>
    @since Thursday, March 01, 2012. 01:59 PM'''
    
    _modem = None
    
    def __init__(self, modem):
        self._modem = modem
        
    def send(self, number, message):
        if not self._modem: return False
        
        sms = messaging.sms.SmsSubmit(number, message)
        modem = self._modem
        for pdu in sms.to_pdu():
            modem.attention('+CMGS=%d' % pdu.length)
            v = modem.attention('%s\x1a' % pdu.pdu, 1, False)
            if v.strip():
                s = 'SMS Send failed. Message from modem: %s' % v
                logging.warning(s)
                return False
        return True
    
    def list(self, status=4):
        modem = self._modem
        pdus = modem.cmgl(status)
        delivers = []
        for index, pdu in pdus.iteritems():
            try:
                deliver = messaging.sms.SmsDeliver(pdu)
            except:
                logging.warning('Undecompiled PDU: %s' % pdu)
                continue
            
            deliver.index = index
            delivers.append(deliver)
        return delivers
    
    def delete(self, index):
        return self._modem.cmgd(index)
    